﻿using Microsoft.Extensions.Hosting;
using System.Collections;
using TriggerInfo = SimpleBoard.Trigger.Trigger;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;

namespace SimpleBoard.Backend.Server.Services.Host
{
    public class TriggerMonitorService : BackgroundService
    {
        private bool running = false;

        private readonly TriggerService triggerService;

        public TriggerMonitorService(TriggerService triggerService)
        {
            this.triggerService = triggerService;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            running = true;
            return Task.CompletedTask;
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            running = false;
            return Task.CompletedTask;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (running)
            {
                for (int i = 0; i < triggerService.PendingTriggers.Count; i++)
                {
                    var trigger = triggerService.PendingTriggers[i];
                    trigger = new(trigger.Item1, trigger.Item2--);
                    triggerService.PendingTriggers[i] = trigger;
                }
                var countedDown = triggerService.PendingTriggers.Where(x => x.Item2 <= 0);

                var removeList = new List<(TriggerInfo, int)>();
                foreach (var trigger in countedDown)
                {
                    if (!trigger.Item1.IsFitConditions())
                    {
                        removeList.Add(trigger);
                        continue;
                    }
                    // 加入执行队列
                    triggerService.ExecutingTriggers.Add(trigger.Item1);
                    // 重置计时
                    triggerService.PendingTriggers.Add(new(trigger.Item1, trigger.Item1.Interval));
                }
                Task.Delay(1000 * 60, stoppingToken);
            }
            return Task.CompletedTask;
        }
    }
}
